package com.hyl.infrastructure.adapter.port;

import com.hyl.domain.trade.adapter.port.ITradePort;
import com.hyl.domain.trade.model.entity.NotifyTaskEntity;
import com.hyl.domain.trade.model.valobj.NotifyTypeEnumVO;
import com.hyl.infrastructure.event.EventPublisher;
import com.hyl.infrastructure.gateway.GroupBuyNotifyService;
import com.hyl.infrastructure.redis.IRedisService;
import com.hyl.types.enums.NotifyTaskHTTPEnumVO;
import io.micrometer.core.instrument.util.TimeUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author hyl
 * @description
 * @create 2025-07-05 17:13
 */
@Service
public class TradePort implements ITradePort {
    @Resource
    private GroupBuyNotifyService groupBuyNotifyService;
    @Resource
    private IRedisService redisService;
    @Resource
    private EventPublisher publisher;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTask) {
        RLock lock = redisService.getLock(notifyTask.lockKey());
        try{
            if (lock.tryLock(3,0, TimeUnit.SECONDS)){
                try {
                    //回调方式http
                    if (NotifyTypeEnumVO.HTTP.getCode().equals(notifyTask.getNotifyType())){
                        if (notifyTask.getNotifyUrl() == null || notifyTask.getNotifyUrl().isEmpty()){
                            return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                        }
                        return groupBuyNotifyService.groupBuyNotify(notifyTask.getNotifyUrl(),notifyTask.getParameterJson());
                    }
                    //回调方式MQ
                    if (NotifyTypeEnumVO.MQ.getCode().equals(notifyTask.getNotifyType())){
                        publisher.publish(notifyTask.getNotifyMQ(), notifyTask.getParameterJson());
                        return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                    }
                }finally {
                    if (lock.isLocked()&&lock.isHeldByCurrentThread()){
                        lock.unlock();
                    }
                }
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }catch (Exception e){
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }
}























